package com.fiveGroup.controller;

import com.fiveGroup.pojo.Address;
import com.fiveGroup.pojo.vo.DataVo;
import com.fiveGroup.service.AddressService;
import com.fiveGroup.util.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 获取用户所有地址
     */
    @GetMapping("/user")
    public DataVo getUserAddresses() {

        List<Address> addresses = addressService.getUserAddresses(UserContextHolder.getUserId());
        return DataVo.success(addresses);
    }

    /**
     * 新增地址
     */
    @PostMapping
    public DataVo addAddress(@RequestBody Address address) {

        address.setUserId(UserContextHolder.getUserId());
        boolean result = addressService.save(address);

        if (result) {
            return DataVo.success();
        }
        return DataVo.fail(400, "新增地址失败");
    }

    /**
     * 更新地址
     */
    @PutMapping
    public DataVo updateAddress(@RequestBody Address address) {
        address.setUserId(UserContextHolder.getUserId());
        boolean result = addressService.updateAddress(address);
        return result ? DataVo.success() : DataVo.fail(400, "更新地址失败");
    }

    /**
     * 删除地址
     */
    @DeleteMapping("/{id}")
    public DataVo deleteAddress(
            @PathVariable Long id,
            @RequestParam Long userId) {

        boolean result = addressService.deleteAddress(id, userId);
        if (result) {
            return DataVo.success();
        }
        return DataVo.fail(400, "删除地址失败");
    }

    @PutMapping("/setDefault/{addressId}")
    public DataVo setDefaultAddress(@PathVariable Long addressId) {
        Address address = new Address();
        address.setUserId(UserContextHolder.getUserId());
        address.setId(addressId);
        address.setIsDefault(1);
        boolean result = addressService.updateAddress(address);
        return result ? DataVo.success() : DataVo.fail(400, "设置默认地址失败");
    }

    /**
     * 获取当前登录用户的所有地址
     * 无需传递userId，自动从登录上下文获取
     */
    @GetMapping("/my")
    public DataVo getMyAddresses() {
        try {
            // 从上下文获取当前登录用户ID（自动校验登录状态）
            Long userId = UserContextHolder.getUserId();
            List<Address> addresses = addressService.getUserAddresses(userId);
            return DataVo.success(addresses);
        } catch (Exception e) {
            // 捕获未登录异常（UserContextHolder会抛出）
            log.error("获取地址失败：", e);
            return DataVo.fail("请先登录");
        }
    }
}
